from flask import Flask, render_template, request, redirect, url_for
from utils.database import get_db, get_users, add_user, update_user, delete_user

app = Flask(__name__)


@app.route('/')
def index():
    with get_db() as db:
        users = get_users(db)
    return render_template('index.html', users=users)


@app.route('/add', methods=['POST'])
def add():
    username = request.form['username']
    role = request.form['role']
    phone = request.form['phone']
    with get_db() as db:
        add_user(db, username, role, phone)
    return redirect(url_for('index'))


@app.route('/update/<int:user_id>', methods=['GET', 'POST'])
def update(user_id):
    if request.method == 'POST':
        username = request.form['username']
        role = request.form['role']
        phone = request.form['phone']
        with get_db() as db:
            update_user(db, user_id, username, role, phone)
        return redirect(url_for('index'))

    with get_db() as db:
        user = db.query(User).filter(User.user_id == user_id).first()
    return render_template('update.html', user=user)


@app.route('/delete/<int:user_id>')
def delete(user_id):
    with get_db() as db:
        delete_user(db, user_id)
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run(debug=True)